import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class GlobalKeyUtils{
  static Future<Uint8List?> toBytes(GlobalKey globalKey)async{
    try{
      var boundary =globalKey.currentContext?.findRenderObject();
      if(boundary!=null){
        final image=await  (boundary as RenderRepaintBoundary).toImage(pixelRatio: 6.0);
        ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
        if(byteData!=null){
          Uint8List pngBytes = byteData.buffer.asUint8List();
          return Future.value(pngBytes);
        }
      }
      return Future.value(null);
    }catch(e){
      return Future.value(null);
    }
  }

  /// 获取当前组件的 RenderBox
  static RenderBox? renderBox(GlobalKey globalKey){
    RenderObject? renderObj = globalKey.currentContext?.findRenderObject();
    if (renderObj == null || renderObj is! RenderBox) {
      return null;
    }
    RenderBox renderBox = renderObj;
    return renderBox;
  }

  /// 获取当前组件的 Offset
  static Offset globalOffset(GlobalKey globalKey) {
    RenderBox? box=renderBox(globalKey);
    if (box== null) {
      return Offset.zero;
    }
    var point = box.localToGlobal(Offset.zero); //组件坐标
    return point;
  }

  /// 获取当前组件的 Size
  static Size globalSize(GlobalKey globalKey) {
    RenderBox? box=renderBox(globalKey);
    if (box == null) {
      return Size.zero;
    }
    return box.size;
  }
}